package com.hmjk.health.family;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class FamilyMemberActivity extends Activity implements OnClickListener{
	private final String TAG = FamilyMemberActivity.class.getSimpleName();
	
	private HealthApp mApp = null;
	
	RelativeLayout mAdmin = null, mAbort = null;//, mAbortSelf = null;	
	Boolean isCreator = false, isAdmin = false;
	String fid, uidMember, uidCreator, uidAdmin, nameString, faname;
	
	private void logd(String info){
		Log.d(TAG,info);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		logd("onCreate");
        super.onCreate(savedInstanceState);
        
        mApp = (HealthApp) this.getApplication();
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.familymember_edit);
        
        mAdmin = (RelativeLayout)findViewById(R.id.setadmin);
        mAbort = (RelativeLayout)findViewById(R.id.abort);
       // mAbortSelf = (RelativeLayout)findViewById(R.id.abortself);
        mAdmin.setOnClickListener(this);
        mAbort.setOnClickListener(this);
       // mAbortSelf.setOnClickListener(this);
        
        Intent i = getIntent();
        isCreator = i.getBooleanExtra("iscreator", isCreator);
        isAdmin = i.getBooleanExtra("isadmin", isAdmin);
       
        fid = i.getStringExtra("fid");
        uidMember = i.getStringExtra("memuid");
        uidCreator = i.getStringExtra("cuid");
        if(i.hasExtra("auid")){
        	uidAdmin = i.getStringExtra("auid");
        }else{
        	uidAdmin = null;
        }
        
        faname = i.getStringExtra("faname");

        TextView tvCreator = (TextView)findViewById(R.id.lv_creator);
        TextView tvAdmin = (TextView)findViewById(R.id.lv_admin);
        TextView tvNormal = (TextView)findViewById(R.id.lv_mem);
        
        tvCreator.setVisibility(uidMember.equals(uidCreator)?View.VISIBLE:View.GONE);
        tvAdmin.setVisibility(uidMember.equals(uidAdmin)?View.VISIBLE:View.GONE);
        tvNormal.setVisibility((uidMember.equals(uidAdmin) || uidMember.equals(uidCreator))?View.GONE:View.VISIBLE);
        
        if(mApp.getUID().equals(uidMember)){
        	mAbort.setVisibility(View.GONE);
        	if(isCreator && (!isAdmin)){
        		mAdmin.setVisibility(View.VISIBLE);
        	}else{
        		mAdmin.setVisibility(View.GONE);
        	}
        	//myself,only show some info
        }else{
	        if((isAdmin && (false == uidMember.equals(uidCreator))) || isCreator){
	        	//i am the admin and this guy is not the creator, i can kick out him
	        	//i am the creator, i can kick out anyone
	        	mAbort.setVisibility(View.VISIBLE);
	        }else{
	        	mAbort.setVisibility(View.GONE);
	        }
	        
	        if(isCreator && (false == uidMember.equals(uidAdmin))){
	        	//i am the creator and this guy is not the admin, i can appoint him as admin 
	        	mAdmin.setVisibility(View.VISIBLE);
	        }else{
	        	mAdmin.setVisibility(View.GONE);
	        }
        }
        nameString = i.getStringExtra("name");
        if((nameString == null) || nameString.isEmpty()){
        	nameString = getResources().getString(R.string.family_default_name);
        }
        TextView mName = (TextView)findViewById(R.id.name);
        mName.setText(nameString);
        
        String statusString = i.getStringExtra("status");
        if((statusString == null) || statusString.isEmpty()){
        	statusString = getResources().getString(R.string.family_default_name);
        }
        TextView mStatus = (TextView)findViewById(R.id.status);
        mStatus.setText(statusString);
        
        ImageButton back = (ImageButton)findViewById(R.id.back);
		back.setOnClickListener(this);
		
	}
	
	@Override
	public void onResume(){
		super.onResume();
		IntentFilter filter = new IntentFilter();
		filter.addAction(DataManager.DATA_COMMIT_RESULT);
		registerReceiver(mReceiver, filter);

	}
	
	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(mReceiver);
	};
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if(action.equals(DataManager.DATA_COMMIT_RESULT)){
				mApp.dismissWaiting();
				String subact = intent.getStringExtra("action");
				if((subact != null) && subact.equals("set_admin")){
					boolean state = intent.getStringExtra("state").equals("00");
					if(state){
						String adminUid = intent.getStringExtra("adminUid");
						try {
							JSONObject commit = new JSONObject();
							if(isAdmin || (uidAdmin == null) || (mApp.getUID().equals(adminUid))){
								//i was the admin and now set another one to be admin
								//or there was no admin,
								//or i was not admin and now set myself to be admin
								//the admin status in falist should be updated
								commit.put("action", "set_admin");
								String fid = intent.getStringExtra("fid");
								commit.put("fid", fid);
								commit.put("adminUid", adminUid);
							
								mApp.getDataManager().commitData(DataManager.F_FAMILYLIST, commit);
							}
							
							mApp.showAlertDialog(FamilyMemberActivity.this, getResources().getString(R.string.family_set_ok), R.string.ok, new OnClickListener() {
								
								@Override
								public void onClick(View arg0) {
									// TODO Auto-generated method stub
									finish();
								}
							});
							return;
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					mApp.showAlertDialog(FamilyMemberActivity.this, R.string.family_set_err);
					finish();
				}else if((subact != null) && subact.startsWith("abort")){
					boolean state = intent.getStringExtra("state").equals("00");
					if(state){
						mApp.showAlertDialog(FamilyMemberActivity.this, getResources().getString(R.string.family_abort_ok), R.string.ok, new OnClickListener() {
							
							@Override
							public void onClick(View arg0) {
								// TODO Auto-generated method stub
								finish();
							}
						});
					}else {
						mApp.showAlertDialog(FamilyMemberActivity.this, R.string.family_abort_err);
						finish();
					}
				}
			}
		}
		
	};
	
	private boolean commitFamilyAdmin(){
		boolean ok = false;
		try {
			mApp.showWaitting(this, null);
			JSONObject commit = new JSONObject();
			
			commit.put("cmd", "setadmin");
			commit.put("fid", fid);
			commit.put("adminuid", uidMember);
			if(uidAdmin != null)
				commit.put("oldadminuid", uidAdmin);
			else
				commit.put("oldadminuid", "");
			
			ok = mApp.getDataManager().commitData(DataManager.F_FAMILYMEMBER, commit);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ok;
	}
	
	private boolean commitAbortMember(){
		boolean ok = false;
		try {
			mApp.showWaitting(this, null);
			JSONObject commit = new JSONObject();
			
			commit.put("cmd", "abortbyadmin");
			commit.put("fid", fid);
			JSONArray uidarray = new JSONArray();
			uidarray.put(uidMember);
			commit.put("uidarray", uidarray);
			
			ok = mApp.getDataManager().commitData(DataManager.F_FAMILYMEMBER, commit);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ok;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.back:{
			finish();
		}break;
		
		case R.id.abort:{
			mApp.showConfirmDialog(this, getResources().getString(R.string.family_abort_cfm, nameString), new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(v.getId() == R.id.alert_but1){
						commitAbortMember();
					}
				}
			});
		}break;
		
		case R.id.setadmin:{
			String cfmString = "";
			
			cfmString = getResources().getString(R.string.family_set_admin_cfm, nameString);
			
			mApp.showConfirmDialog(this, cfmString, new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(v.getId() == R.id.alert_but1){
						commitFamilyAdmin();
					}
				}
			});
		}break;
		}
	}

}
